# -*- coding: utf-8 -*- 


file_with_data = 'wiki2.txt'
file_to_be_cut = 'morfo2.txt'
output_file = 'morfo3.txt'

print 'Rozpoczynam przycinanie pliku ' + file_to_be_cut
print 'Dane pomocniczne zostana pobrane z pliku ' + file_with_data
print 'Wynik zostanie zapisany w pliku ' + output_file

f1 = open(file_with_data)
set1 = set()
i = 0

for line in f1:
    i += 1
    if i % 1000000 == 0:
        print i
        break
    lineSplit = line.split()
    for elem in  lineSplit:
        set1.add(elem)

f2 = open(file_to_be_cut)

for line in f1:
    i += 1
    if i % 1000000 == 0:
        print i
        break
    lineSplit = line.split()
    for elem in  lineSplit:
        set1.add(elem)

f2 = open(file_to_be_cut)

i = 0 


outDicto = {}

def addToDicto(line):
    word = line.split()[0]
    lista = line.split()[1:]
    if word in outDicto:
        outDicto[word] += lista
    else:
        outDicto[word] = lista

for line in f2:
    i += 1
    if i % 100000 == 0:
        print i
    logic = False
    lineSplit = line.split()
    for elem in lineSplit:
        if elem in set1:
            logic = True
            break
    if logic:
        addToDicto(line)


f3 = open(output_file,'w')

for elem in outDicto:
    f3.write(elem + ' ')
    for elem2 in outDicto[elem]:
        f3.write(elem2 + ' ')
    f3.write('\n')      

f3.close()

